<!--  -->
<template>
  <div class="cart">
    <header>
      <div class="heade" v-for="item in state.box">
        <van-icon name="checked" color="#8b0000" size="14px" />
        <span>{{ item }}</span>
      </div>
    </header>
    <cartBox
      :cartList="state.cartList"
      @change="changeCheck"
      @setChange="setChange"
      @checkedChange="checkedChange"
    ></cartBox>
    <van-submit-bar
      :price="state.checkedGoodsAmount"
      button-text="提交订单"
      style="margin-bottom: 50px"
    >
      <!-- @submit="onSubmit" -->
      <van-checkbox v-model="checked">全选</van-checkbox>
      <!-- <template #tip> 你的收货地址不支持配送 </template> -->
    </van-submit-bar>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, watch } from "vue";
import { getCartData, goodsSelectApi } from "@/api/api.ts";
import cartBox from "./components/cartBox.vue";

let checked = ref(false);
let status = ref(true);
const state = reactive({
  box: ["30天无忧退货", "48小时快速退货", "满88元免邮费"],
  // 总金额
  checkedGoodsAmount: 0,
  // 购物车数据
  cartList: [],
});
const getCart = async () => {
  const res = await getCartData();
  console.log(res, "购物车数据");
  // checked.value = res.data.
  state.cartList = res.data.cartList;
  state.checkedGoodsAmount = res.data.cartTotal.checkedGoodsAmount * 100;
  // console.log(state.cartList);
  const sta = state.cartList.every((item) => {
    return item.checked === 1;
  });
  // status.value = false;
  checked.value = sta === true ? true : false;
};
const changeCheck = (res) => {
  console.log(res);
  getCart();
};
const setChange = (res) => {
  getCart();
};
const checkedChange = (res) => {
  //
  status.value = false;
  checked.value = res;
  console.log(res);
};
watch(
  () => checked.value,
  () => {
    if (checked.value === true) {
      for (let item of state.cartList) {
        console.log(item);
        goodsSelectApi({
          isChecked: 1,
          productIds: item.product_id,
        }).then((res) => {
          getCart();
        });
      }
    } else {
      if (status.value) {
        for (let item of state.cartList) {
          console.log(item);
          goodsSelectApi({
            isChecked: 0,
            productIds: item.product_id,
          }).then((res) => {
            getCart();
          });
        }
      }
      status.value = true;
    }
  }
);
onMounted(() => {
  getCart();
});
</script>

<style lang="scss" scoped>
header {
  height: 60px;
  width: 100%;
  background-color: #efefef;
  display: flex;
  justify-content: space-around;
  font-size: 28px;
  align-items: center;
}
</style>
